<!-- src/views/SubjectManagement.vue -->
<template>
    <div class="page-container">
        <!-- 页面头部 -->
        <PageHeader title="科目管理">
            <!-- 搜索和筛选区域 -->
            <template #search-filters>
                <!-- 科目搜索 -->
                <div class="subject-search">
                    <span class="label">科目搜索：</span>
                    <el-tooltip content="支持搜索科目代码或名称" placement="top">
                        <el-icon class="help-icon"><QuestionFilled /></el-icon>
                    </el-tooltip>
                    <el-input 
                        v-model="searchKeyword" 
                        placeholder="搜索科目代码或名称" 
                        style="width: 300px"
                        clearable 
                        @input="handleSearch"
                    />
                </div>

                <!-- 状态筛选 -->
                <div class="subject-status-select">
                    <span class="label">状态筛选：</span>
                    <el-tooltip content="选择科目状态进行筛选" placement="top">
                        <el-icon class="help-icon"><QuestionFilled /></el-icon>
                    </el-tooltip>
                    <el-select 
                        v-model="filterStatus" 
                        placeholder="状态筛选" 
                        clearable 
                        style="width: 150px"
                        @change="loadData"
                    >
                        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </div>
            </template>

            <!-- 主要操作按钮 -->
            <template #main-actions>
                <el-button type="primary" @click="handleCreate" v-permission="'subject:manage'">
                    <el-icon><Plus /></el-icon>
                    新建科目
                </el-button>
            </template>

            <!-- 更多操作下拉菜单 -->
            <template #more-actions>
                <el-dropdown @command="handleMoreAction">
                    <el-button type="info">
                        <el-icon><More /></el-icon>
                        更多
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="reset" icon="Refresh">重置筛选</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </template>
        </PageHeader>

        <!-- 数据表格 -->
        <div class="table-container">
            <el-table :data="pageData" style="width: 100%" size="medium" stripe row-key="id" height="100%"
                header-row-class-name="fixed-header">
                <el-table-column prop="subjectCode" label="科目代码" min-width="120" fixed />
                <el-table-column label="科目名称" min-width="200">
                    <template #default="{ row }">
                        <span :style="{ paddingLeft: (row.subjectLevel - 1) * 20 + 'px' }">
                            {{ row.subjectName }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="subjectDescription" label="描述" min-width="250" show-overflow-tooltip />
                <el-table-column prop="subjectLevel" label="级别" width="80" align="center" />
                <el-table-column label="叶子节点" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.isLeaf ? 'success' : 'info'">
                            {{ row.isLeaf ? '是' : '否' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="statusMap[row.status]?.type || 'info'">
                            {{ statusMap[row.status]?.label || '未知' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="220" fixed="right">
                    <template #default="{ row }">
                        <div class="action-buttons">
                            <el-button link type="primary" @click="editSubject(row)">编辑</el-button>
                            <el-divider direction="vertical" />
                            <el-button link :type="row.status === 1 ? 'danger' : 'success'" @click="toggleStatus(row)">
                                {{ row.status === 1 ? '停用' : '启用' }}
                            </el-button>
                            <el-divider direction="vertical" />
                            <el-button link type="danger" @click="handleDelete(row.id)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-wrapper">
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="totalItems"
                    layout="total, sizes, prev, pager, next, jumper"
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </div>

        <!-- 科目表单对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEditMode ? '编辑科目' : '新建科目'" width="680px">
            <el-form :model="formData" label-width="100px" :rules="formRules" ref="formRef">
                <el-form-item label="科目代码" prop="subjectCode">
                    <el-input v-model="formData.subjectCode" :disabled="isEditMode" />
                </el-form-item>
                <el-form-item label="科目名称" prop="subjectName">
                    <el-input v-model="formData.subjectName" />
                </el-form-item>
                <el-form-item label="父级科目">
                    <el-cascader v-model="formData.parentSubjectId" :options="subjectTree" :props="cascaderProps"
                        clearable filterable style="width: 100%" />
                </el-form-item>
                <el-form-item label="科目描述">
                    <el-input v-model="formData.subjectDescription" type="textarea" :rows="3" />
                </el-form-item>
                <el-form-item label="是否叶子" prop="isLeaf">
                    <el-switch v-model="formData.isLeaf" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="formData.status">
                        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, QuestionFilled, More } from '@element-plus/icons-vue'
import {
    getSubjects,
    getSubjectTree,
    createSubject,
    updateSubject,
    deleteSubject,
    updateSubjectStatus
} from '@/api/subjectApi'
import { debounce } from 'lodash-es'
import PageHeader from '@/components/layout/PageHeader.vue'

// 状态配置
const statusMap = {
    0: { label: '停用', type: 'danger' },
    1: { label: '启用', type: 'success' }
}

const statusOptions = Object.entries(statusMap).map(([value, item]) => ({
    value: Number(value),
    label: item.label
}))

// 级联选择器配置
const cascaderProps = {
    value: 'id',
    label: 'subjectName',
    checkStrictly: true,
    emitPath: false
}

// 表单初始数据
const initFormData = () => ({
    subjectCode: '',
    subjectName: '',
    subjectDescription: '',
    parentSubjectId: null,
    isLeaf: false,
    status: 1
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(20)
const totalItems = ref(0)
const pageData = ref([])
const searchKeyword = ref('')
const filterStatus = ref(null)
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formData = ref(initFormData())
const formRef = ref(null)
const subjectTree = ref([])

// 表单验证规则
const formRules = {
    subjectCode: [
        { required: true, message: '请输入科目代码', trigger: 'blur' },
        { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
    ],
    subjectName: [
        { required: true, message: '请输入科目名称', trigger: 'blur' },
        { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
    ]
}

// 加载数据
const loadData = async () => {
    try {
        const params = {
            page: currentPage.value,
            size: pageSize.value,
            search: searchKeyword.value,
            status: filterStatus.value
        }
        const res = await getSubjects(params)
        pageData.value = res.data.content
        totalItems.value = res.data.total
    } catch (error) {
        ElMessage.error(`数据加载失败: ${error.message}`)
    }
}

// 加载科目树
const loadSubjectTree = async () => {
    try {
        const res = await getSubjectTree()
        subjectTree.value = res.data
    } catch (error) {
        ElMessage.error('科目树加载失败')
    }
}

// 搜索处理
const handleSearch = debounce(loadData, 500)

// 更多操作处理
const handleMoreAction = (command) => {
    switch (command) {
        case 'reset':
            searchKeyword.value = ''
            filterStatus.value = null
            loadData()
            break
        default:
            break
    }
}

// 分页处理
const handleSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
    loadData()
}

const handleCurrentChange = (page) => {
    currentPage.value = page
    loadData()
}

// 打开创建对话框
const handleCreate = async () => {
    await loadSubjectTree()
    dialogVisible.value = true
    isEditMode.value = false
    formData.value = initFormData()
}

// 打开编辑对话框
const editSubject = async (row) => {
    await loadSubjectTree()
    dialogVisible.value = true
    isEditMode.value = true
    formData.value = {
        ...row,
        parentSubjectId: row.parentSubjectId
    }
}

// 提交表单
const submitForm = async () => {
    try {
        await formRef.value.validate()

        const payload = {
            ...formData.value,
            parentSubject: formData.value.parentSubjectId ? { id: formData.value.parentSubjectId } : null
        }

        if (isEditMode.value) {
            await updateSubject(formData.value.id, payload)
        } else {
            await createSubject(payload)
        }

        ElMessage.success('操作成功')
        dialogVisible.value = false
        loadData()
    } catch (error) {
        ElMessage.error(`操作失败: ${error.message}`)
    }
}

// 删除处理
const handleDelete = async (id) => {
    try {
        await ElMessageBox.confirm('确定删除该科目吗？', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        await deleteSubject(id)
        ElMessage.success('删除成功')
        loadData()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

// 切换状态
const toggleStatus = async (row) => {
    try {
        const newStatus = row.status === 1 ? 0 : 1
        await updateSubjectStatus(row.id, newStatus)
        ElMessage.success('状态更新成功')
        loadData()
    } catch (error) {
        ElMessage.error('状态更新失败')
    }
}

onMounted(() => {
    loadData()
    loadSubjectTree()
})
</script>

<style scoped>
@import '/src/assets/css/common.css';
@import '/src/styles/page.css';

/* 搜索区域样式 */
.subject-search {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-right: 20px;
}

.subject-status-select {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-right: 20px;
}

.label {
    font-size: 14px;
    color: var(--el-text-color-regular);
    white-space: nowrap;
}

.help-icon {
    color: var(--el-text-color-secondary);
    cursor: help;
}

/* 表格容器样式 */
.table-container {
    flex: 1;
    min-height: 0;
    overflow: auto;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    border: 1px solid rgba(0, 0, 0, 0.05);
}

.action-buttons {
    display: flex;
    align-items: center;
}

/* 分页器样式 */
.pagination-wrapper {
    padding: 15px;
    background: white;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #eee;
    flex-shrink: 0;
}
</style>